# -*- coding: utf-8 -*-
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from main.forms import RestApplayForm
from main.models import Rest_apply, Rest
from pub import utils
from urllib2 import HTTPRedirectHandler


#餐厅加盟申请列表
@login_required
def listRestApply(request, template_name="space/service/rest_apply_list.html"):
    restApplyList = Rest_apply.objects.all().order_by('-reg_time')
    return render_to_response(template_name,{'list':restApplyList},context_instance=RequestContext(request))

#审核餐厅加盟申请
@login_required
def auditRestApply(request,pk=None, template_name="space/service/rest_apply_audit.html"):
    restApply = Rest_apply.objects.get(pk = pk)
    if request.method == "POST":
        restApply.audited = True
        if request.POST.get('passed'):
            restApply.passed = True
            restApply.user.groups.remove(Group.objects.get(name__iexact="rest_apply"))
            restApply.user.groups.add(Group.objects.get(name__iexact="rest"))
            rest = Rest()
            rest.user = restApply.user
            rest.name = restApply.name
            rest.phone = restApply.phone
            rest.mobile = restApply.user.username
            rest.state = True
            rest.save()
            restApply.save()
            utils.send_sms(restApply.user.username, "你的餐厅会员申请已通过");
        else:
            restApply.passed = False
            restApply.save()
            utils.send_sms(restApply.user.username, "你的餐厅会员申请失败");
        return HttpResponseRedirect("/space/service/rests/apply/")
    else:
        return render_to_response(template_name,{'rest_apply':restApply},context_instance=RequestContext(request))
